package cn.iocoder.yudao.boot.banner.core;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.iocoder.yudao.boot.web.config.WebProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.stereotype.Component;

import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * 项目启动成功后，提供文档相关的地址
 *

 */
@Slf4j
public class BannerApplicationRunner implements ApplicationRunner {

    @Autowired
    private ServletWebServerApplicationContext servletWebServerApplicationContext;

    private WebProperties webProperties;

    public BannerApplicationRunner(WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    public void run(ApplicationArguments args) {
        Integer port = servletWebServerApplicationContext.getWebServer().getPort();
        String contextPath = servletWebServerApplicationContext.getServletContext().getContextPath();
        StringBuilder uriBui = new StringBuilder();
        uriBui.append(NetUtil.getLocalhostStr()).append(":").append(port);
        if (StringUtils.isNotBlank(contextPath)) {
            uriBui.append("/").append(contextPath);
        }

        ThreadUtil.execute(() -> {
            ThreadUtil.sleep(1, TimeUnit.SECONDS); // 延迟 1 秒，保证输出到结尾
            StringJoiner strJoi = new StringJoiner("\n\t");
            strJoi.add("\n")
                    .add("----------------------------------------------------------")
                    .add("项目启动成功！")
                    .add("接口文档: http://" + uriBui.toString() + "/doc.html")
                    .add("----------------------------------------------------------")
            ;
            log.info(strJoi.toString());
        });
    }

}
